// 根据环境不同引入不同api地址
import { baseApi } from '@/config'
import { Toast } from 'vant'
import qs from 'qs'
// let CT = 'application/x-www-form-urlencoded'
let CT = 'application/json'
async function service(obj) {
  try {
    if (!obj.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true
      })
    }
    if (obj.headers && obj.headers['Content-Type']) {
      CT = obj.headers['Content-Type']
    }
    const headers = { Accept: 'application/json, text/plain, */*' }
    let st = sessionStorage.getItem('Authorization')
    if (st) {
      headers['Authorization'] = st // 请求头带上token
    }
    headers['Content-Type'] = CT
    let response = null
    if (obj.method && obj.method.toLocaleLowerCase() == 'post') {
      let body = ''
      if (obj.data) {
        body = JSON.stringify(obj.data)
      }
      let res = await fetch(baseApi + obj.url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        headers,
        body
      })
      response = await res.json()
      if (response.status && response.status !== 200) {
        // 登录超时,重新登录
        if (response.status === 401) {
          sessionStorage.removeItem('Authorization')
          setTimeout(() => {
            window.location.href =
              'https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1&servicecode=xjszhq&goto=https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2001832445/reserved/index.html?debug=true'
          }, 300)
        }
        return Promise.reject(res || 'error')
      }
    } else {
      delete headers['Content-Type']
      let url = baseApi + obj.url
      let data = ''
      let params = ''
      let opParams = ''
      if (obj.params) {
        params = qs.stringify(filterNullProsties(obj.params) )
      }
      if (obj.data) {
        data = qs.stringify(filterNullProsties(obj.data))
      }
      if (params && data) {
        opParams = params + '&' + data
      } else if (params) {
        opParams = params
      } else if (data) {
        opParams = data
      }
      if (url.includes('?') && opParams) {
        url = url + '&' + opParams
      } else if (opParams) {
        url = url + '?' + opParams
      }
      let res = await fetch(url, { headers })
      response = await res.json()
    }
    Toast.clear()
    return response
  } catch (error) {
    Toast.clear()
    console.log('err' + error) // for debug
    throw error
  }
}
function filterNullProsties(obj = {}) {
  obj = JSON.parse(JSON.stringify(obj))
  for (let key of Object.keys(obj)) {
    if (obj[key] !== 0 && obj[key] !== false && !obj[key]) {
      delete obj[key]
    }
  }
  return obj
}
export function monitorTrace(monitorType, module, modulePoint, bizInfo = {}) {
  ZWJSBridge.onReady(() => {
    ZWJSBridge.monitorTrace({
      monitorType,
      module,
      modulePoint,
      bizInfo
    })
  })
}

export default service
